/* * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.franmontiel.persistentcookiejar;

import com.franmontiel.persistentcookiejar.cache.SetCookieCache;

import okhttp3.Cookie;

import java.util.Arrays;
import java.util.Collections;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

/**
 * This class is used to test cookie is set or not
 */
public class SetCookieCacheTest {
    /**
     * This method is used to clear all cookies & check whether its cleared or not
     */
    @Test
    public void clear_ShouldClearAllCookies() {
        SetCookieCache cache = new SetCookieCache();
        Cookie cookie = TestCookieCreator.createPersistentCookie(false);
        cache.addAll(Collections.singletonList(cookie));
        cache.clear();
        assertFalse(cache.iterator().hasNext());
    }

    /**
     * Cookie equality used to update: same cookie-name, domain-value, and path-value.
     */
    @Test
    public void addAllCookieEqualsToOneAlreadyAddedShouldUpdateTheStoreCookie() {
        SetCookieCache cache = new SetCookieCache();
        cache.addAll(Collections.singleton(
                TestCookieCreator.createNonPersistentCookie("name", "first")));
        Cookie newCookie = TestCookieCreator.createNonPersistentCookie("name", "last");
        cache.addAll(Collections.singleton(newCookie));
        Cookie addedCookie = cache.iterator().next();
        assertEquals(newCookie, addedCookie);
    }

    /**
     * This is not RFC Compliant but strange things happen in the real world and it is intended to maintain
     * a common behavior between Cache and Persistor
     * <p>
     * Cookie equality used to update: same cookie-name, domain-value, and path-value.
     */
    @Test
    public void addAll_WithMultipleEqualCookies_LastOneShouldBeAdded() {
        SetCookieCache cache = new SetCookieCache();
        Cookie equalCookieThatShouldNotBeAdded = TestCookieCreator.createPersistentCookie("name", "first");
        Cookie equalCookieThatShouldBeAdded = TestCookieCreator.createPersistentCookie("name", "last");
        cache.addAll(Arrays.asList(equalCookieThatShouldNotBeAdded, equalCookieThatShouldBeAdded));
        Cookie addedCookie = cache.iterator().next();
        assertEquals(equalCookieThatShouldBeAdded, addedCookie);
    }
}